//
//  PersonalVC.m
//  UHealth
//
//  Created by hanyou on 15/3/18.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "PersonalVC.h"
#import "UserObj.h"
#import "AppDelegate.h"
#import "PersonalVCCell.h"
#import "UUDatePicker.h"
#import "NavView.h"
#import "DBManage.h"
#import "NSString+BloodSugar.h"
#import "iToast.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"

#import "DLAVAlertView.h"

#import "VPImageCropperViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>

#import "UIImageView+WebCache.h"

#import "PersonalPickerView.h"


#define ORIGINAL_MAX_WIDTH 640.0f

@interface PersonalVC ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate, VPImageCropperDelegate,UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic, strong)  UITableView        *contentTableView;
@property (nonatomic, strong)  NSMutableArray     *dataArray;

@property (nonatomic, strong) UserObj             *user;

@property (nonatomic,strong) UIPickerView           *hPick;
@property (nonatomic,strong) UIPickerView           *wPick;

@property (nonatomic,strong) UUDatePicker           *datePicker;

@property (nonatomic,strong) UIImage                *myImg;
@property (nonatomic)       BOOL                    isChangeImg;

///** pickerView */
//@property (nonatomic, weak) PersonalPickerView *pickerView;

/** 选择器弹窗 */
@property (nonatomic, weak) UIButton *pickerPop;
/** 选择器占位 */
@property (weak, nonatomic) UIView *pickerPlace;

/** 导航栏 */
@property (nonatomic, weak) NavView *nav;
@end

@implementation PersonalVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view.backgroundColor = kBacColor;
    }
    return self;
}

- (void)setTitleName:(NSString *)titleName {
    _titleName = titleName;
    
    self.nav.titleName = _titleName;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *titleName = self.titleName ? self.titleName : kLocal(@"personInfo");
    
    NavView *nav = [[NavView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, kNavHeight) andTitleStr:titleName andVC:self];
    [self.view addSubview:nav];
    self.nav = nav;
    
    //更新个人资料按钮
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    saveBtn.frame = CGRectMake(WIDTH - 55, 21, 40, 40);
    [saveBtn setTitle:kLocal(@"save_btn") forState:UIControlStateNormal];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    saveBtn.tag = 3;
    [nav addSubview:saveBtn];
    
    //列表
    _dataArray = [NSMutableArray arrayWithObjects:
                  @[kLocal(@"photo"),kLocal(@"account_number"),kLocal(@"name"),kLocal(@"telephone"),kLocal(@"modify_pw")],@[kLocal(@"birthday"),kLocal(@"sex"),kLocal(@"height"),kLocal(@"weight")], nil];
    
    _user = [[DBManage sharedManager] getUserWithID:0];
    
    _contentTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNavHeight, self.view.frame.size.width, HEIGHT - 20 - 40-kNavHeight - 10) style:UITableViewStyleGrouped];
    _contentTableView.delegate = self;
    _contentTableView.dataSource = self;
    [_contentTableView setSeparatorInset:UIEdgeInsetsZero];
    [self.view addSubview:_contentTableView];
    
    //注销
    if (kNetID) {//注册了才有注销按钮
        UIButton *cancellationBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        if (VIEW_3_5_INCH) {
            cancellationBtn.frame = CGRectMake(40, HEIGHT - 20 - 40, WIDTH - 80, 40);
        }else{
            cancellationBtn.frame = CGRectMake(40, HEIGHT - 30 - 40, WIDTH - 80, 40);
        }
        [cancellationBtn.layer setMasksToBounds:YES];
        [cancellationBtn.layer setCornerRadius:1.0];//设置矩形是个圆角半径
        cancellationBtn.backgroundColor = kBlueColor;
        [cancellationBtn setTitle:kLocal(@"cancellation") forState:UIControlStateNormal];
        [cancellationBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cancellationBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:cancellationBtn];
    }
    
    //时间选择
    _datePicker
    = [[UUDatePicker alloc]initWithframe:CGRectMake(0, 30, WIDTH, 186)
                             PickerStyle:UUDateStyle_YearMonthDay
                             didSelected:^(NSString *year,
                                           NSString *month,
                                           NSString *day,
                                           NSString *hour,
                                           NSString *minute,
                                           NSString *weekDay) {
                                 _user.birthDate = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
                                 
                             }];
    _datePicker.backgroundColor = kBacColor;
    
    _datePicker.ScrollToDate = [NSDate dateFromString:_user.birthDate withFormat:@"YYYY-MM-dd"];
    if ((int)_user.height >=100) {
        [_hPick selectRow:(int)_user.height - 100 inComponent:0 animated:NO];
    }
    if ((int)_user.weight >=30) {
        [_wPick selectRow:(int)_user.weight - 30 inComponent:0 animated:NO];
    }
    
    
    //身高选择
    _hPick = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 30 , WIDTH, 186)];
    _hPick.delegate = self;
    _hPick.dataSource = self;
    _hPick.backgroundColor = kBacColor;
    [_hPick selectRow:30 inComponent:0 animated:NO];//设置选中行
    
    
    //体重选择
    _wPick = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 30, WIDTH, 186)];
    _wPick.delegate = self;
    _wPick.dataSource = self;
    _wPick.backgroundColor = kBacColor;
    
    [_wPick selectRow:9 inComponent:0 animated:NO];//设置选中行
    
    
    //    // 通用pickerView
    //    PersonalPickerView *pickerView = [PersonalPickerView pickerView];
    //    CGRect  frame = pickerView.frame;
    //    frame.origin.y = kScreenHeight;
    //    pickerView.frame = frame;
    //    pickerView.completion = ^{
    //        [self.contentTableView reloadData];
    //    };
    //    self.pickerView = pickerView;
    //
    //    [self.view addSubview:pickerView];
    
    
    
    // 选择器弹窗
    UIButton *pickerPop = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    pickerPop.backgroundColor = [UIColor clearColor];
    [pickerPop addTarget:self action:@selector(dismissTheButton:) forControlEvents:UIControlEventTouchUpInside];
    
    // 用来添加 pickerView
    UIView *pickerPlace = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight-216, kScreenWidth, 216)];
    pickerPlace.backgroundColor = kBacColor;
    [pickerPop addSubview:pickerPlace];
    self.pickerPlace = pickerPlace;
    
    UIView *toolBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    toolBar.backgroundColor = kBacColor;
    [pickerPlace addSubview:toolBar];
    
    UIButton *doneButton = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-60, 0, 60, 30)];
    doneButton.backgroundColor = [UIColor whiteColor];
    doneButton.layer.masksToBounds = YES;
    doneButton.layer.cornerRadius = 8;
    [doneButton setTitle:kLocal(@"sure") forState:UIControlStateNormal];
    doneButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [doneButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [doneButton addTarget:self action:@selector(dismissTheButton:) forControlEvents:UIControlEventTouchUpInside];
    [toolBar addSubview:doneButton];
    
    self.pickerPop = pickerPop;
    
    [self.view addSubview:pickerPop];
    self.pickerPop.hidden = YES;
    
    
    
    // Do any additional setup after loading the view.
}

- (void)dismissTheButton:(UIButton *)btn {
    [self.contentTableView reloadData];
    self.pickerPop.hidden = YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - func按钮
-(void)BtnClick:(UIButton *)btn
{
    if(btn.tag == 3){
        if (kNetID) {//注册了
            _isChangeImg = NO;
            if (!kNetIsOK) {
                [[iToast makeText:kLocal(@"netNoOK")]show];
                [_contentTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
                return;
            }
            MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
            [self.view addSubview:HUD];
            HUD.labelText = kLocal(@"update_info");
            [HUD show:YES];
            
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.requestSerializer.timeoutInterval = 10;
            manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
            NSString *postStr = [NSString stringWithFormat:@"%@/action/json/login.jsp",kBaseUrl];
            NSDictionary *parameters = @{@"action": @"memberinfoedit",
                                         @"userid":[NSString stringWithFormat:@"%ld",(long)kNetID],
                                         @"famid":[NSString stringWithFormat:@"%d",_user.famID],
                                         @"mem_name":_user.name,
                                         @"mem_birth":_user.birthDate,
                                         @"mem_sex":[NSString stringWithFormat:@"%d",_user.sex],
                                         @"men_shengao":[NSString stringWithFormat:@"%d",(int)_user.height],
                                         @"men_tizhong":[NSString stringWithFormat:@"%d",(int)_user.weight],
                                         @"mem_province":@"0",
                                         @"mem_city":@"0",
                                         @"mem_area":@"0",
                                         @"filenum":[NSString stringWithFormat:@"%d",_myImg != nil],
                                         @"mem_mobile":[[NSUserDefaults standardUserDefaults] objectForKey:kNetUserPhone],
                                         @"xt_standardvalue":@{@"timetype1":@"6.0",@"timetype2":@"10.0",@"timetype3":@"4.5",@"timetype4":@"5.9",@"timetype5":@"5.0",@"timetype6":@"6.9",@"timetype7":@"7.9"}};
            [manager POST:postStr parameters:parameters constructingBodyWithBlock:^(id formData){
                
                if (_myImg) {
                    [formData appendPartWithFileData:UIImagePNGRepresentation(_myImg) name:@"img0" fileName:@"img0.png" mimeType:@"image/png"];
                }
                //                [formData appendPartWithFileURL:[NSURL fileURLWithPath:kPostImgFilePath] name:@"img0" error:nil];
                
            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                kDebug(@"Success: %@", operation.responseString);
                BOOL type = [[responseObject objectForKey:@"type"] boolValue];
                if(type){
                    _user.headImg = responseObject[@"imgpath"];
                    
                    NSString *setStr = [NSString stringWithFormat:@"%@ = '%@',%@ = '%@',%@ = '%d',%@ = '%@',%@ = '%f',%@ = '%f'",kUserHeadImg,_user.headImg,kUserName,_user.name,kUserSex,_user.sex,kUserBirthDate,_user.birthDate,kUserHeight,_user.height,kUserWeight,_user.weight];
                    NSString *conStr = [NSString stringWithFormat:@"%@ = '%d'",kFamID,_user.famID];
                    [[DBManage sharedManager] updateData:setStr andTable:kUserTable andConditions:conStr];
                    
                    [[DBManage sharedManager] setValue:_user forKey:kFirstUser];//变更KVO通知 BLE--User 回收到通知
                    [[iToast makeText:[responseObject objectForKey:@"msg"]] show];
                    [HUD hide:NO];
                    [self dismissViewControllerAnimated:YES completion:nil];
                }else{
                    [HUD hide:NO];
                    [[iToast makeText:[responseObject objectForKey:@"msg"]] show];
                    [_contentTableView reloadData];
                }
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {//网络失败本地取
                kDebug(@"Error: %@", error);
                [HUD hide:NO];
                [[iToast makeText:kLocal(@"netError")]show];
                [_contentTableView reloadData];
            }];
        }else{//未注册 直接存到数据库
            NSString *setStr = [NSString stringWithFormat:@"%@ = '%@',%@ = '%@',%@ = '%d',%@ = '%@',%@ = '%f',%@ = '%f'",kUserHeadImg,_user.headImg,kUserName,_user.name,kUserSex,_user.sex,kUserBirthDate,_user.birthDate,kUserHeight,_user.height,kUserWeight,_user.weight];
            NSString *conStr = [NSString stringWithFormat:@"%@ = '%d'",kFamID,_user.famID];
            [[DBManage sharedManager] updateData:setStr andTable:kUserTable andConditions:conStr];
            
            [[DBManage sharedManager] setValue:_user forKey:kFirstUser];//变更KVO通知 BLE--User 回收到通知
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }else{
        DLAVAlertView *alertView = [[DLAVAlertView alloc] initWithTitle:kLocal(@"cancellation") message:nil delegate:nil cancelButtonTitle:kLocal(@"cancel") otherButtonTitles:kLocal(@"sure"), nil];
        [alertView showWithCompletion:^(DLAVAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
                [def removeObjectForKey:kNetUserID];
                [def removeObjectForKey:kNetUserName];
                [def removeObjectForKey:kNetUserPhone];
                [def synchronize];
                
                AppDelegate *delegate = [UIApplication sharedApplication].delegate;
                [delegate changRootVCToLaunch];
            }
            
        }];
    }
}



#pragma mark - UITableViewDelegate && UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray[section] count];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0 ) {
        return 60;
    }
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSArray *arr = _dataArray[indexPath.section];
    //    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (indexPath.row == 0 && indexPath.section == 0) {
        
        [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PersonalVCCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([PersonalVCCell class])];
        PersonalVCCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PersonalVCCell class]) forIndexPath:indexPath];
        cell.Title.text = arr[indexPath.row];
        if (_isChangeImg) {
            [cell.Img setImage:_myImg];
        }else{
            [cell.Img sd_setImageWithURL:[NSURL URLWithString:_user.headImg] placeholderImage:[UIImage imageNamed:@"user"]];
        }
        
        
        return cell;
    }else{
        static NSString *ID =@"cellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if(cell == nil){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
        }
        cell.textLabel.text = arr[indexPath.row];
        NSString *str ;
        if (indexPath.section == 0) {
            
            switch (indexPath.row) {
                case 1:
                    str = [[NSUserDefaults standardUserDefaults] objectForKey:kNetUserName];//[NSString stringWithFormat:@"%ld",(long)kNetID]
                    break;
                case 2:
                    str = _user.name;
                    break;
                case 3:
                    str = [[NSUserDefaults standardUserDefaults] objectForKey:kNetUserPhone];
                    break;
                    
                default:
                    break;
            }
        }else{
            
            switch (indexPath.row) {
                case 0:
                    if ([_user.birthDate isEqualToString:@"(null)"]) {
                        str = @" ";
                    }else{
                        str = _user.birthDate;
                    }
                    break;
                case 1:{
                    str = kLocal(@"male");
                    if(_user.sex){
                        str = kLocal(@"female");
                    }
                }
                    break;
                case 2:
                    if (_user.height == 0) {
                        str = @" ";
                    }else{
                        str = [NSString stringWithFormat:@"%dcm",(int)_user.height];
                    }
                    break;
                case 3:
                    if (_user.weight == 0) {
                        str = @" ";
                    }else{
                        str = [NSString stringWithFormat:@"%dkg",(int)_user.weight];
                    }
                    break;
                    
                default:
                    break;
            }
        }
        cell.detailTextLabel.text =str;
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0://头像
                [self editPortrait];
                break;
            case 2:{//姓名
                DLAVAlertView *alertView = [[DLAVAlertView alloc] initWithTitle:kLocal(@"modify_name") message:nil delegate:nil cancelButtonTitle:kLocal(@"cancel") otherButtonTitles:kLocal(@"sure"), nil];
                alertView.alertViewStyle = DLAVAlertViewStylePlainTextInput;
                [alertView showWithCompletion:^(DLAVAlertView *alertView, NSInteger buttonIndex) {
                    if (buttonIndex == 1) {
                        _user.name = [alertView textFieldAtIndex:0].text;
                        [tableView reloadData];
                        
                    }
                    
                }];
            }
                break;
            case 3:{//改手机
                
                //                DLAVAlertView *alertView = [[DLAVAlertView alloc] initWithTitle:@"修改手机号码" message:nil delegate:nil cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
                //                alertView.alertViewStyle = DLAVAlertViewStylePlainTextInput;
                //                UITextField *f = [alertView textFieldAtIndex:0];
                //                f.keyboardType = UIKeyboardTypeNumberPad;
                //                [alertView showWithCompletion:^(DLAVAlertView *alertView, NSInteger buttonIndex) {
                //                    if (buttonIndex == 1) {
                //                        if ([alertView textFieldAtIndex:0].text.length == 11 ) {
                //                            [[NSUserDefaults standardUserDefaults] setObject:[alertView textFieldAtIndex:0].text forKey:kNetUserPhone];
                //                            [tableView reloadData];
                //                        }else{
                //                            [[iToast makeText:@"号码不正确"]show];
                //                        }
                //                    }
                //
                //                }];
            }
                break;
            case 4:{//改密
                [self changePW];
            }
                break;
                
            default:
                break;
        }
    }else if(indexPath.section == 1){
        switch (indexPath.row) {
            case 0:{//出生
                [UIView animateWithDuration:0.5 animations:^{
                    self.pickerPop.hidden = NO;
                    [self.pickerPlace addSubview:_datePicker];
                } completion:^(BOOL finished) {
                }];
            }
                break;
            case 1:{//性别
                UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                         delegate:self
                                                                cancelButtonTitle:kLocal(@"cancel")
                                                           destructiveButtonTitle:kLocal(@"female")
                                                                otherButtonTitles:kLocal(@"male"),nil];
                choiceSheet.tag = 11;
                [choiceSheet showInView:self.view];
            }
                break;
            case 2:{//身高
                [UIView animateWithDuration:0.5 animations:^{
                    self.pickerPop.hidden = NO;
                    [self.pickerPlace addSubview:_hPick];
                } completion:^(BOOL finished) {
                }];
            }
                break;
            case 3:{//体重
                [UIView animateWithDuration:0.5 animations:^{
                    self.pickerPop.hidden = NO;
                    [self.pickerPlace addSubview:_wPick];
                } completion:^(BOOL finished) {
                }];
            }
                
                break;
            default:
                break;
        }
    }
    
}


-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_hPick.center.y == HEIGHT-100 ||
        _wPick.center.y == HEIGHT-100 ||
        _datePicker.center.y == HEIGHT-100) {
        
        [UIView animateWithDuration:0.5 animations:^{
            _hPick.center = CGPointMake(WIDTH/2, HEIGHT+100);
            _wPick.center = CGPointMake(WIDTH/2, HEIGHT+100);
            _datePicker.center = CGPointMake(WIDTH/2, HEIGHT+100);
        } completion:^(BOOL finished) {
            [_contentTableView reloadData];
        }];
    }
    return indexPath;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}


#pragma mark - 改密
-(void)changePW{
    if(!kNetID){
        [[iToast makeText:kLocal(@"notLogin")] show];
        return;
    }
    if (!kNetIsOK) {
        [[iToast makeText:kLocal(@"netNoOk")] show];
        return;
    }
    DLAVAlertView *alertView = [[DLAVAlertView alloc] initWithTitle:kLocal(@"modify_pw")  message:nil delegate:nil cancelButtonTitle:kLocal(@"cancel") otherButtonTitles:kLocal(@"sure") , nil];
    alertView.alertViewStyle = DLAVAlertViewStyleLoginAndPasswordInput;
    [alertView textFieldAtIndex:0].placeholder = kLocal(@"old_pw");
    [alertView textFieldAtIndex:0].secureTextEntry = YES;
    [alertView textFieldAtIndex:1].placeholder = kLocal(@"new_pw");
    [alertView textFieldAtIndex:1].secureTextEntry = YES;
    [alertView showWithCompletion:^(DLAVAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            NSString *str1 = [alertView textFieldAtIndex:1].text;
            NSString *str = [alertView textFieldAtIndex:0].text;
            
            if(str1.length >= 6 && str1.length <=12){
                AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
                manager.requestSerializer.timeoutInterval = 10;
                manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
                
                NSString *postStr = [NSString stringWithFormat:@"%@/action/json/login.jsp",kBaseUrl];
                NSDictionary *parameters = @{@"action": @"setpwd",
                                             @"userid":[NSString stringWithFormat:@"%ld",(long)kNetID],
                                             @"foruserid":[NSString stringWithFormat:@"%d",_user.famID],
                                             @"password":str1,
                                             @"password_old":str};
                [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    //                            kDebug(@"Success: %@", operation.responseString);
                    BOOL type = [[responseObject objectForKey:@"type"] boolValue];
                    if(type){
                    }else{
                    }
                    [[iToast makeText:[responseObject objectForKey:@"msg"]] show];
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {//网络失败本地取
                    kDebug(@"Error: %@", error);
                    [[iToast makeText:kLocal(@"netError")] show];
                }];
            }else{
                [[iToast makeText:kLocal(@"pw_length_error")] show];
            }
            
        }
    }];
}



#pragma mark - 选择器

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if ([_wPick isEqual:pickerView]) {
        return 121;
    }
    return 150;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if ([_wPick isEqual:pickerView]) {
        return [NSString stringWithFormat:@"%3d kg",6 + (int)row];
    }
    return  [NSString stringWithFormat:@"%3d cm",60 + (int)row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if ([_wPick isEqual:pickerView]) {
        _user.weight = 6+row;
    }else{
        _user.height = 60+row;
    }
}

#pragma mark - 触摸
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_hPick.center.y == HEIGHT-100 ||
        _wPick.center.y == HEIGHT-100 ||
        _datePicker.center.y == HEIGHT-100) {
        
        [UIView animateWithDuration:5 animations:^{
            _hPick.center = CGPointMake(WIDTH/2, HEIGHT+100);
            _wPick.center = CGPointMake(WIDTH/2, HEIGHT+100);
            _datePicker.center = CGPointMake(WIDTH/2, HEIGHT+100);
        } completion:^(BOOL finished) {
            [_contentTableView reloadData];
        }];
    }
    
    
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
    
}


#pragma mark - 头像

#pragma mark portraitImageView getter

- (void)editPortrait {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:kLocal(@"cancel")
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:kLocal(@"take_pic"), kLocal(@"select_from_album"), nil];
    choiceSheet.tag = 0;
    [choiceSheet showInView:self.view];
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    _myImg = editedImage;
    _isChangeImg = YES;
    [_contentTableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
    }];
    
    
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet.tag == 0) {//头像选择
        
        if (buttonIndex == 0) {
            // 拍照
            if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
                UIImagePickerController *controller = [[UIImagePickerController alloc] init];
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                if ([self isFrontCameraAvailable]) {
                    controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
                }
                NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
                [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
                controller.mediaTypes = mediaTypes;
                controller.delegate = self;
                [self presentViewController:controller
                                   animated:YES
                                 completion:^(void){
                                 }];
            }
            
        } else if (buttonIndex == 1) {
            // 从相册中选取
            if ([self isPhotoLibraryAvailable]) {
                UIImagePickerController *controller = [[UIImagePickerController alloc] init];
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
                [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
                controller.mediaTypes = mediaTypes;
                controller.delegate = self;
                [self presentViewController:controller
                                   animated:YES
                                 completion:^(void){
                                 }];
            }
        }
    }else if(actionSheet.tag == 11){//性别男女选择
        if(buttonIndex<2){
            _user.sex = !buttonIndex;
            [_contentTableView reloadData];
        }
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}


#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        kDebug(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}





/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
